package hhm.android.machine.bluetooth

import android.Manifest
import android.bluetooth.BluetoothAdapter
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.tbruyelle.rxpermissions3.RxPermissions
import com.trello.rxlifecycle4.RxLifecycle
import com.trello.rxlifecycle4.android.ActivityEvent
import hhm.android.library.utils.GetStringListener
import hhm.android.library.utils.OnMultiClickListener
import hhm.android.machine.R
import siau.android.base.*
import siau.android.http.model.DeviceIdModel
import siau.android.http.model.DeviceModel
import siau.android.http.model.UpdateDeviceInfoRequest
import siau.android.library.KeyString

@Route(path = BLUETOOTH_MACHINE_ROUTE)
class ToothBrushMachineActivity : SBBaseActivity() {
    private val locationPermissions = arrayOf(
        Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION
    )
    lateinit var data: DeviceModel//接口返回的对象
    private val REQUEST_ENBLE_BT = 5555
    var bean: MyBlueToothBean? = null//本地蓝牙对象
    lateinit var stateTv: TextView
    lateinit var btn: TextView
    lateinit var reset: Button
    lateinit var machineName: TextView
    lateinit var machineNameLl: LinearLayout

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setTitleWhiteAndTextBlank()
        setContentView(R.layout.activity_toothbrush_machine)

        stateTv = findViewById(R.id.activity_toothbrush_machine_tv_state)
        btn = findViewById(R.id.activity_toothbrush_machine_btn)
        reset = findViewById(R.id.activity_toothbrush_machine_reset)

        machineName = findViewById(R.id.activity_toothbrush_machine_name)
        machineNameLl = findViewById(R.id.activity_toothbrush_machine_name_ll)

        if (SBApplication.userData.isCreator != 1) {
            btn.visibility = View.GONE
        }

        data = intent.getSerializableExtra(KeyString.data) as DeviceModel

        initTitleWithLine(data.productName)
        machineName.text = data.deviceName

        SBApplication.getBlueToothUtils()

        //检查蓝牙是否连接
        if (SBApplication.getBlueToothUtils().connectDevice?.size!! > 0) {
            checkNeedLoading()
        } else {
            if (SBApplication.getBlueToothUtils().mBluetoothAdapter == null) {
                showToast("当前设备不支持蓝牙")
                return
            }

            val rxPermissions = RxPermissions(this)
            rxPermissions.request(*locationPermissions).subscribe {
                if (it) {
                    // 没有打开蓝牙
                    if (!SBApplication.getBlueToothUtils().mBluetoothAdapter.isEnabled) {
                        val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
                        startActivityForResult(enableBtIntent, REQUEST_ENBLE_BT)
                    } else {
                        SBApplication.getBlueToothUtils().pairBlueTooth()
                    }
                } else {
                    showToast("蓝牙功能需要获取GPS位置权限才能扫描到设备")
                }
            }
        }

        btn.setOnClickListener(object : OnMultiClickListener() {
            override fun onMultiClick(v: View?) {
                getSureDialog(this@ToothBrushMachineActivity, {
//                    if (SBApplication.startCalculate.value == true && SBApplication.calculateType == 2) {
//                        SBApplication.startCalculate.value = false
//                    }
                    showLoadingFragment(R.id.activity_toothbrush_machine_fl)
                    val r = DeviceIdModel(data.deviceId)
                    HttpHelper().unbindDevice(r)?.compose(RxLifecycle.bindUntilEvent(lifecycle(), ActivityEvent.STOP))?.subscribe({
                        removeLoadingFragment()
                        showToast(getString(R.string.unbind_success))
                        if (bean != null) {
                            SBApplication.getBlueToothUtils().disConnect(bean)
                            SBApplication.getBlueToothUtils().connectDevice.remove(bean)
                        }
                        var removeBean: DeviceModel? = null
                        SBApplication.userData.deviceList?.forEach {
                            if (it.bluetoothCode == data.bluetoothCode) {
                                removeBean = it
                            }
                        }
                        if (removeBean != null) {
                            SBApplication.userData.deviceList?.remove(removeBean)
                        }
                        SBApplication.getBlueToothUtils().setControlCallback(null)
                        SBApplication.hasWeightMachine = false
                        SBApplication.hasHeightMachine = false
                        SBApplication.hasToothBrushMachine = false
                        SBApplication.userData.deviceList?.forEach { d ->
                            when (d.deviceType) {
                                1 -> {
                                    SBApplication.hasWeightMachine = true
                                }
                                2 -> {
                                    SBApplication.hasHeightMachine = true
                                }
                                3 -> {
                                    SBApplication.hasToothBrushMachine = true
                                }
                            }
                        }
                        ARouter.getInstance().build(MAIN_ROUTER).withFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK).navigation()
                    }, {
                        removeLoadingFragment()
                        showToast(it.message)
                    })
                }, content = getString(R.string.sure_delete_device), showTitle = false)
            }
        })
        machineNameLl.setOnClickListener(object : OnMultiClickListener() {
            override fun onMultiClick(v: View?) {
                if (SBApplication.userData.isCreator == 1) {
                    getStringDialog(this@ToothBrushMachineActivity, getString(R.string.get_machine_name), "", object : GetStringListener {
                        override fun getString(s: String) {
                            showLoadingFragment(R.id.activity_toothbrush_machine_fl)
                            val r = UpdateDeviceInfoRequest(data.deviceId, s)
                            HttpHelper().updateDeviceInfo(r)?.compose(RxLifecycle.bindUntilEvent(lifecycle(), ActivityEvent.STOP))?.subscribe({
                                removeLoadingFragment()
                                machineName.text = s
                            }, {
                                removeLoadingFragment()
                                showToast(it.message)
                            })
                        }
                    })
                }
            }
        })

        SBApplication.getBlueToothUtils().connectDeviceNum?.observe(this, {
            checkNeedLoading()
        })
    }

    private fun checkNeedLoading() {
        bean = null
        SBApplication.getBlueToothUtils().connectDevice?.forEach {
            if (it.bluetoothCode.equals(data.bluetoothCode)) {
                bean = it
            }
        }
        if (bean == null) {
            stateTv.text = getString(R.string.unconnected)
            reset.isEnabled = false
            reset.setBackgroundResource(R.drawable.rectangle_circle_14_grey_e6)
            SBApplication.getBlueToothUtils().setControlCallback(null)
        } else {
            stateTv.text = getString(R.string.connected)
            reset.isEnabled = true
            reset.setBackgroundResource(R.drawable.rectangle_circle_14_89e4ff)
            SBApplication.getBlueToothUtils().setControlCallback(control)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_ENBLE_BT && resultCode == RESULT_OK) {
            SBApplication.getBlueToothUtils().pairBlueTooth()
        } else if (requestCode == REQUEST_ENBLE_BT && resultCode != RESULT_OK) {
            showToast("请打开手机蓝牙后再试")
        }
    }

    private val control = object : BlueToothUtil.ControlCallBack {
        override fun voiceOpenSuccess(blueToothCode: String) {
            if (bean?.bluetoothCode == blueToothCode) {
                removeLoadingFragment()
            }
        }

        override fun voiceCloseSuccess(blueToothCode: String) {
            if (bean?.bluetoothCode == blueToothCode) {
                removeLoadingFragment()
            }
        }

        override fun shoeSizeOpenSuccess(blueToothCode: String) {
            if (bean?.bluetoothCode == blueToothCode) {
                removeLoadingFragment()
            }
        }

        override fun shoeSizeCloseSuccess(blueToothCode: String) {
            if (bean?.bluetoothCode == blueToothCode) {
                removeLoadingFragment()
            }
        }

        override fun simpleVoiceOpenSuccess(blueToothCode: String) {
            if (bean?.bluetoothCode == blueToothCode) {
                removeLoadingFragment()
            }
        }

        override fun simpleVoiceCloseSuccess(blueToothCode: String) {
            if (bean?.bluetoothCode == blueToothCode) {
                removeLoadingFragment()
            }
        }

        override fun classCMtoFTSuccess(blueToothCode: String) {
            if (bean?.bluetoothCode == blueToothCode) {
                removeLoadingFragment()
            }
        }

        override fun classFTtoCMSuccess(blueToothCode: String) {
            if (bean?.bluetoothCode == blueToothCode) {
                removeLoadingFragment()
            }
        }

        override fun classLBtoKGSuccess(blueToothCode: String) {
            if (bean?.bluetoothCode == blueToothCode) {
                removeLoadingFragment()
            }
        }

        override fun classKGtoLBSuccess(blueToothCode: String) {
            if (bean?.bluetoothCode == blueToothCode) {
                removeLoadingFragment()
            }
        }
    }

    override fun onBackPressed() {
        if (findLoadingFragment() != null) {
            removeLoadingFragment()
        } else {
            SBApplication.getBlueToothUtils().setControlCallback(null)
            super.onBackPressed()
        }
    }
}